<!-- <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <form action="" id="form">
    选择文件：<input type="file" name="f"><br>
    <input type="button" value="上传" id="btn">
  </form>
  <script>
    //1.获取按钮注册点击事件
    document.getElementById('btn').onclick = function(){
      //2.获取要上传的文件 通过 FormData表单对象
      // 1)获取form的DOM对象
      var form = document.getElementById('form');
      // 2)实例化FormData对象，并将form作为参数传入
      var fd = new FormData(form);

      //3.发送ajax请求 并将文件一起发送给后端
      var xhr = new XMLHttpRequest();
      xhr.open('post','/api/upload');
      xhr.send(fd);
      xhr.onload = function(){
        alert(xhr.responseText);
      };
    };
  </script>
</body>
</html> -->


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    /* span{
      position: absolute;
      left: 145px;
      top:15px;
      display: none;
    } */
  </style>
</head>
<body>
  <!-- 外层的div只是进度条的边框 -->
  <div style="width: 300px; height: 30px; border: 1px solid red;">
    <!-- 内层的div才是真正的进度条 -->
    <div style="height: 30px;" id="progress"></div>
    <!-- 进度条中显示完成上传任务的百分比 -->
    <span style="position: absolute; left: 145px; top: 15px; display: none;">0%</span>
  </div>
  <form action="" id="form">
    选择文件：<input type="file" name="f"><br>
    <input type="button" id="btn" value="上传"><br>
  </form>
  <script>
    document.getElementById('btn').onclick = function(){
      var form = document.getElementById('form');
      var fd = new FormData(form);

      var xhr = new XMLHttpRequest();
      console.log(xhr)
      
      var progress = document.getElementById('progress');
      var span = document.querySelector('span');

      xhr.upload.onprogress = function(e){
        var percent = parseInt((e.loaded / e.total)*100);
        console.log(percent)
        progress.style.width = percent +'%';
        progress.style.backgroundColor = 'red';

        if(percent >= 0){
          span.style.display = 'block';
        }
        span.innerText = percent +'%';
      };

      xhr.open('post','/api/upload');
      xhr.send(fd);
      // xhr.onload = function(){
      //   alert(xhr.responseText);
      // };
    };
  </script>
</body>
</html>